<template>
  <div class="users">
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card class="box-card">

      <!-- 头部搜索 -->
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input placeholder="请输入内容" v-model="queryInfo.query" clearable @clear="getUsersList">
            <el-button slot="append" icon="el-icon-search" @click="getUsersList"></el-button>
          </el-input>
        </el-col>

        <el-col :span="4">
          <el-button type="primary" @click="dialogVisible = true">添加用户</el-button>
        </el-col>
      </el-row>

      <!-- 用户展示 -->
      <el-table :data="usersList" border stripe>
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column prop="username" label="姓名"></el-table-column>
        <el-table-column prop="email" label="邮箱"></el-table-column>
        <el-table-column prop="mobile" label="电话"></el-table-column>
        <el-table-column prop="role_name" label="角色"></el-table-column>
        <el-table-column prop="mg_state" label="状态">
          <template v-slot="scoped">
            <el-switch v-model="scoped.row.mg_state" active-color="#13ce66" inactive-color="#dddee2"
              @change="changeState(scoped.row)"></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template v-slot="scoped">
            <!-- 修改按钮 -->
            <el-button type="primary" icon="el-icon-edit" @click="chanegUserInfo(scoped.row.id)"></el-button>

            <!-- 删除按钮 -->
            <el-button type="danger" icon="el-icon-delete" @click="deleteUser(scoped.row.id)"></el-button>

            <!-- 分配角色按钮 -->
            <el-tooltip effect="dark" content="分配角色" placement="top-start" :enterable="false">
              <el-button type="warning" icon="el-icon-setting" @click="setRoleDiaglose(scoped.row)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <!-- 页脚 -->
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum" :page-sizes="[1, 2, 5, 10]" :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>

      <!-- 添加用户弹窗 -->
      <el-dialog title="添加用户" :visible.sync="dialogVisible" width="50%" @close="dialogClose">
        <!-- 表单区域 -->
        <el-form :model="addUserInfo" :rules="addUserRules" ref="addUserRef" label-width="70px">
          <el-form-item label="用户名" prop="userName">
            <el-input v-model="addUserInfo.userName"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input v-model="addUserInfo.password"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="addUserInfo.email"></el-input>
          </el-form-item>
          <el-form-item label="手机" prop="mobile">
            <el-input v-model="addUserInfo.mobile"></el-input>
          </el-form-item>
        </el-form>

        <!-- 弹窗底部按钮 -->
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addUser">确 定</el-button>
        </span>
      </el-dialog>

      <!-- 修改用户弹窗 -->
      <el-dialog title="提示" :visible.sync="dialogChangeVisible" width="50%" @close="dislogEditClose()">

        <!-- 表单区域 -->
        <el-form ref="editForm" :model="userInfo" label-width="80px" :rules="editUsersRules">
          <el-form-item label="用户名">
            <el-input v-model="userInfo.username" disabled></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="userInfo.email"></el-input>
          </el-form-item>
          <el-form-item label="手机号" prop="mobile">
            <el-input v-model="userInfo.mobile"></el-input>
          </el-form-item>
        </el-form>

        <!-- 弹窗底部按钮 -->
        <span slot="footer">
          <el-button @click="dialogChangeVisible = false">取 消</el-button>
          <el-button type="primary" @click="editUser">确 定</el-button>
        </span>
      </el-dialog>

      <!-- 用户分配角色弹窗 -->
      <el-dialog title="提示" :visible.sync="dialogSetRoleVisible" width="50%" @close="setRoleDiagloseClose">
        <div>
          <p>当前的用户：{{ user.username }}</p>
          <p>当前的用户：{{ user.role_name }}</p>
          <p>
            分配新的角色：
            <el-select v-model="selectRoleID" placeholder="请选择">
              <el-option v-for="item in roleList" :key="item.id" :label="item.roleName" :value="item.id"></el-option>
            </el-select>
          </p>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogSetRoleVisible = false">取 消</el-button>
          <el-button type="primary" @click="setRole">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
export default {
  data () {
    const checkmobile = (rule, value, callback) => {
      const regmobile = /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/
      if (regmobile.test(value)) return callback()
      callback(new Error('请输入合法的手机号'))
    }
    const checkEmail = (rule, value, callback) => {
      const regmobile = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
      if (regmobile.test(value)) return callback()
      callback(new Error('请输入合法的邮箱'))
    }
    return {
      queryInfo: {
        query: '',
        pagenum: 1,
        pagesize: 2
      },
      addUserInfo: {
        userName: 'xiaonan',
        password: '123456',
        email: '115@qq.com',
        mobile: '18914774599'
      },
      userInfo: {
      },
      usersList: [],
      user: {},
      total: 0,
      dialogVisible: false, // 控制新建用户弹窗
      dialogChangeVisible: false,
      dialogSetRoleVisible: false,
      roleList: [],
      selectRoleID: '',
      addUserRules: { // 校验用户规则
        userName: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 3, max: 15, message: '长度在 3 到 15 个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入电话号码', trigger: 'blur' },
          { validator: checkmobile, trigger: 'blur' }
        ]
      },
      editUsersRules: {
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入电话号码', trigger: 'blur' },
          { validator: checkmobile, trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    async getUsersList () {
      const { data: res } = await this.$http.get('users', { params: this.queryInfo })
      if (res.meta.status !== 200) return this.$message.error('获取用户列表失败')
      this.usersList = res.data.users
      this.total = res.data.total
    },
    handleSizeChange (newVal) {
      this.queryInfo.pagesize = newVal
      this.getUsersList()
    },
    handleCurrentChange (newVal) {
      this.queryInfo.pagenum = newVal
      this.getUsersList()
    },
    async changeState (userInfo) {
      const { data: res } = await this.$http.put(`users/${userInfo.id}/state/${userInfo.mg_state}`)
      if (res.meta.status !== 200) {
        userInfo.mg_state = !userInfo.mg_state
        return this.$message.error('修改状态失败')
      }
      this.$message.success('修改成功')
    },
    dialogClose () {
      this.$refs.addUserRef.resetFields()
    },
    addUser () {
      this.$refs.addUserRef.validate(async valid => {
        if (!valid) return this.$message.error('请将信息填写完整')
        const { userName: username, password, email, mobile } = this.addUserInfo
        const { data: res } = await this.$http.post('users', { username, email, password, mobile })
        if (res.meta.status !== 201) return this.$message.error('添加失败')
        this.$message.success('添加成功')
        this.getUsersList()
        this.dialogVisible = false
      })
    },
    async chanegUserInfo (id) {
      const { data: res } = await this.$http.get(`users/${id}`)
      if (res.meta.status !== 200) return this.$message.error('网络异常')
      this.userInfo = res.data
      this.dialogChangeVisible = true
    },
    dislogEditClose () {
      this.$refs.editForm.resetFields()
    },
    editUser () {
      this.$refs.editForm.validate(async (valid) => {
        if (!valid) return this.$message.error('信息不合法')
        const { data: res } = await this.$http.put(`users/${this.userInfo.id}`, { email: this.userInfo.email, mobile: this.userInfo.mobile })
        if (res.meta.status !== 200) return this.message.error('网络请求错误,修改失败')
        this.dialogChangeVisible = false
        this.$message.success('更新成功')
        this.getUsersList()
      })
    },
    deleteUser (id) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const { data: res } = await this.$http.delete(`users/${id}`)
        if (res.meta.status !== 200) return this.$message.error('删除失败')
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
        this.getUsersList()
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    async setRoleDiaglose (role) {
      this.dialogSetRoleVisible = true
      this.user = role
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) return this.$message.error('网络异常')
      this.roleList = res.data
    },
    async setRole () {
      if (!this.selectRoleID) return this.$message.error('请将用户信息填写完整')
      const { data: res } = await this.$http.put(`users/${this.user.id}/role`, { rid: this.selectRoleID })
      if (res.meta.status !== 200) return this.$message.error('网络异常')
      this.$message.success('更新成功')
      this.dialogSetRoleVisible = false
      this.getUsersList()
    },
    setRoleDiagloseClose () {
      this.user = {}
      this.selectRoleID = ''
    }
  },
  created () {
    this.getUsersList()
  }
}
</script>

<style lang="scss" scoped></style>
